<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :label-width="formInfo.labelWidth"
              :rules="formInfo.rules"
            >
              <template v-slot:form-estimateStartTime1>
                <select-model
                  v-model.lazy="formInfo.data.borrowDeptName1"
                  :type-code="`asset_cost_project`"
                  width="50%"
                  @change="changeCapitalSource($event, scope.$index)"
                />
                <select-model
                  v-model.lazy="formInfo.data.borrowDeptName2"
                  :type-code="`asset_cost_project`"
                  width="50%"
                  @change="changeCapitalSource($event, scope.$index)"
                />
              </template>

              <template v-slot:form-depotName>
                <el-input
                  class="not-mongolia"
                  :disabled="true"
                  placeholder="请选择领入仓库"
                  v-model="formInfo.data.depotName"
                >
                  <template #append>
                    <el-icon @click="selectDepotStorage"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-useDeptName>
                <el-input
                  v-model="formInfo.data.useDeptName"
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择领用部门"
                >
                  <template #append>
                    <el-icon @click="selectDept"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-exportDepotName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择领出仓库"
                  v-model="formInfo.data.exportDepotName"
                >
                  <template #append>
                    <el-icon @click="selectDepotExport"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-deptName>
                <el-input
                  class="not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择消耗部门"
                  v-model="formInfo.data.deptName"
                >
                  <template #append>
                    <el-icon @click="selectConsumeDept"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-contactName>
                <el-input
                  v-model="formInfo.data.contactName"
                  class="not-br not-mongolia"
                  type="input"
                  :disabled="true"
                  placeholder="请选择领用人"
                >
                  <template #append>
                    <el-icon @click="openUser"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-remindTime>
                <el-date-picker
                  v-model="formInfo.data.remindTime"
                  type="datetime"
                  disabled
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="提醒时间"
                >
                </el-date-picker>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>明细信息</p>
          </div>
          <div class="model-panel-body borrowing-box">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addAsset>
                <el-button :disabled="props.orderId" @click="addAsset()"
                  >添加产品</el-button
                >
              </template>
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-btnSlotArr>
                <el-form
                  :inline="true"
                  :model="formFilter"
                  class="demo-form-inline"
                >
                  <el-form-item label="领用数量策略：" labelWidth="120px">
                    <select-model
                      v-model.lazy="formFilter.borrowDeptName"
                      :type-code="`asset_cost_project`"
                      width="100%"
                      @change="changeCapitalSource($event, scope.$index)"
                    />
                  </el-form-item>
                  <el-form-item label="领用数量: ">
                    <el-input-number
                      v-model.lazy="formFilter.estimatePowerUp"
                      clearable
                      controls-position="right"
                      :precision="0"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      :disabled="!canSettingAsset"
                      type="primary"
                      @click="allSetting"
                      >一键设置</el-button
                    >
                  </el-form-item>
                </el-form>
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isRowClickSelect="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span
                      class="slip-edit"
                      @click="showProductDetail(scope.row)"
                    >
                      {{ scope.row.assetName || '-' }}
                    </span>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 添加资产 -->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="false"
      :highlightRow="true"
      @callback="callBackAsset"
    />
    <!-- 选择领入仓库 -->
    <SelectDepot
      v-if="depotInfo.visible"
      v-model:showDialog="depotInfo.visible"
      @callback="selectStoreDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :query="depotInfo.query"
      :highlightRow="true"
    />
    <!-- 选择领出仓库 -->
    <SelectDepot
      v-if="exportDepotInfo.visible"
      v-model:showDialog="exportDepotInfo.visible"
      @callback="selectExportDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :api="exportDepotInfo.api"
      :query="exportDepotInfo.query"
      :highlightRow="true"
    />
    <!-- 选择领入部门 -->
    <SelectDept
      v-if="deptInfo.visible"
      v-model:show-dialog="deptInfo.visible"
      :query="deptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :save-empty="true"
      @callback="selectDeptCallback"
    />
    <!-- 选择领出部门 -->
    <select-dept
      v-if="deptInfoExport.visible"
      v-model:showDialog="deptInfoExport.visible"
      :query="deptInfoExport.query"
      @callback="selectDeptExportCallback"
      :checkBox="false"
      :highlightRow="true"
      :saveEmpty="true"
    />
    <SelectUsers
      v-if="selectUserInfo.visible"
      v-model:show-dialog="selectUserInfo.visible"
      :query="selectUserInfo.query"
      :check-box="false"
      :highlight-row="true"
      :api="getOrganizationPage"
      :save-empty="true"
      @callback="selectUserInfoBack"
    />
  </div>
</template>

<script setup name="equipmentUpDownModify">
import PageForm from '@/components/PageForm/index'
import {
  addUseManagePage,
  updateUseManagePage,
  getUseManageById,
} from '@/api/asset.js'
import { getDepotPage } from '@/api/core'
import utils from '@/common/js/utils'
import { getCustomizeSetting } from '@/api/customize'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'id', 'title'])
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      // assetSourceAuth: {
      //   asTbName: 'core_asset,core_asset',
      //   columnName: 'use_dept_id,depot_id',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'assetSourceAuth',
      // },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
    },
    queryParams: {
      assetUserAndManaDeptAuth: true,
    },
  },
})
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '规则名称', value: 'patientName', type: 'input' },
    { label: '执行周期', value: 'sex', type: 'select-model', code: 'sex' },
    { label: '执行日期', value: 'estimateStartTime1', type: 'slot' },
    {
      label: '领入仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '领用部门',
      value: 'useDeptName',
      type: 'slot',
    },
    {
      label: '领出仓库',
      value: 'exportDepotName',
      type: 'slot',
    },
    {
      label: '领出部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '领用人',
      value: 'contactName',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    patientName: [
      { required: true, message: '请输入规则名称', trigger: 'blur' },
    ],
    sex: [{ required: true, message: '请选择执行周期', trigger: 'blur' }],
    estimateStartTime1: [
      { required: true, message: '请选择执行日期', trigger: 'blur' },
    ],
    depotName: [{ required: true, message: '请选择领入仓库', trigger: 'blur' }],
    useDeptName: [
      { required: true, message: '请选择领用部门', trigger: 'blur' },
    ],
    contactName: [{ required: true, message: '请选择领用人', trigger: 'blur' }],
  },
  labelWidth: '140px',
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
// 一键设置表单
const formFilter = ref({})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addAsset' },
    { type: 'slot', value: 'removeAsset' },
    { type: 'slot', value: 'btnSlotArr' },
  ],
})
const depotInfo = ref({
  visible: false,
  depotType: '',
  query: {
    idNot: '',
    useTypeId: '1',
    status: '1',
  },
})
const exportDepotInfo = ref({
  visible: false,
  depotType: '',
  api: getDepotPage,
  query: {
    useTypeId: '1',
    status: '1',
    idMult: '',
    idNot: '',
  },
})
const deptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const deptInfoExport = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const selectUserInfo = ref({
  visible: false,
  query: {
    status: 1,
    idNotIn: '',
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: function (row) {
          return !props.orderId
        },
      },
    ],
  },
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length && !props.orderId
})
//选择领入仓库
function selectDepotStorage() {
  depotInfo.value.depotType = 'storage'
  depotInfo.value.query.depotAuth = 'id'
  depotInfo.value.visible = true
  depotInfo.value.query.subDepotId = ''
  depotInfo.value.query.isCargoSpaceManage = 0
}
//选择领出仓库
function selectDepotExport() {
  exportDepotInfo.value.depotType = 'export'
  exportDepotInfo.value.api = getDepotPage
  exportDepotInfo.value.visible = true
}
function selectDept() {
  deptInfo.value.visible = true
  deptInfo.value.query.idNotIn = formInfo.value.data.useDeptId
}
function openUser() {
  selectUserInfo.value.visible = true
  selectUserInfo.value.query.idNotIn = formInfo.value.data.contact
}
function selectConsumeDept() {
  deptInfoExport.visible = true
}
function selectStoreDepotCallback(row) {
  if (row && row.id) {
    if (formInfo.value.data.depotId !== row.id) {
      tableInfo.value.data = []
      formInfo.value.data.depotId = row.id
      formInfo.value.data.depotName = row.name
      formInfo.value.data.deptName = row.deptName
      formInfo.value.data.deptId = row.deptId
      formInfo.value.supDepotIds = row.supDepotIds
      formInfo.value.data.exportDepotName = ''
      formInfo.value.data.exportDepotId = ''
      formInfo.value.data.exportDeptName = ''
      formInfo.value.data.exportDeptId = ''
    }
    productInfo.value.query.queryParams.storeDepotId = row.id
    //领出仓库必填时自动带出领出仓库
    if (
      systemConfig.value.use_application_export_depot_required_strategy === 1
    ) {
      getExportDopotId(formInfo.value.data.depotId)
    } else {
      getProductList()
    }
  } else {
    tableInfo.value.data = []
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    formInfo.value.data.exportDepotName = ''
    formInfo.value.data.exportDepotId = ''
    formInfo.value.data.exportDeptName = ''
    formInfo.value.data.exportDeptId = ''
    productInfo.value.query.queryParams.storeDepotId = ''
    formInfo.value.supDepotIds = []
  }
}
function selectExportDepotCallback(row) {
  if (row && row.id) {
    if (formInfo.value.data.exportDepotId !== row.id) {
      tableInfo.value.data = []
      formInfo.value.data.exportDepotId = row.id
      formInfo.value.data.exportDepotName = row.name
      formInfo.value.data.exportDeptName = row.deptName ? row.deptName : ''
      formInfo.value.data.exportDeptId = row.deptId ? row.deptId : ''
    }
    productInfo.value.query.queryParams.exportDepotId = row.id
  } else {
    tableInfo.value.data = []
    formInfo.value.data.exportDepotId = ''
    formInfo.value.data.exportDepotName = ''
    formInfo.value.data.exportDeptName = ''
    formInfo.value.data.exportDeptId = ''
    productInfo.value.query.queryParams.exportDepotId = ''
  }
}
function selectDeptCallback(row) {
  if (row && row.id) {
    formInfo.value.data.useDeptName = row.name
    formInfo.value.data.useDeptId = row.id
  } else {
    formInfo.value.data.useDeptName = ''
    formInfo.value.data.useDeptId = ''
  }
}
function selectDeptExportCallback(row) {
  if (row) {
    formInfo.data.deptName = row.name
    formInfo.data.deptId = row.id
  } else {
    formInfo.data.deptName = ''
    formInfo.data.deptId = ''
  }
}
function selectUserInfoBack(data) {
  if (data && data.id) {
    formInfo.value.data.contactName = data.name
    formInfo.value.data.contact = data.id
    formInfo.value.data.phone = data.tel || ''
  } else {
    formInfo.value.data.contactName = ''
    formInfo.value.data.contact = ''
    formInfo.value.data.phone = ''
  }
}
//选择资产
function addAsset() {
  selectAssetInfo.value.visible = true
}

function callBackAsset(data) {
  console.log(data)
  if (data && data.id) {
    formInfo.value.data['assetId'] = data.id
    formInfo.value.data['assetName'] = data.assetName
    formInfo.value.data['assetCode'] = data.assetCode
    formInfo.value.data['standard'] = data.standard
    formInfo.value.data['brandName'] = data.brandName
    formInfo.value.data['useDeptName'] = data.useDeptNameRate
    formInfo.value.data['useDeptId'] = data.useDeptId

    formInfo.value.data['supplierId'] = data.supplierId
    formInfo.value.data['supplierName'] = data.supplierName
    formInfo.value.data['depotName'] = data.depotName
    formInfo.value.data['depotId'] = data.depotId
    formInfo.value.data['manageDeptName'] = data.manageDeptName
    formInfo.value.data['manageDeptId'] = data.manageDeptId
    formInfo.value.data['location'] = data.location
  } else {
    formInfo.value.data['assetId'] = ''
    formInfo.value.data['assetName'] = ''
    formInfo.value.data['assetCode'] = ''
    formInfo.value.data['standard'] = ''
    formInfo.value.data['brandName'] = ''
    formInfo.value.data['useDeptName'] = ''
    formInfo.value.data['useDeptId'] = ''

    formInfo.value.data['supplierId'] = ''
    formInfo.value.data['supplierName'] = ''
    formInfo.value.data['depotName'] = ''
    formInfo.value.data['depotId'] = ''
    formInfo.value.data['manageDeptName'] = ''
    formInfo.value.data['manageDeptId'] = ''
    formInfo.value.data['location'] = ''
  }
}

onMounted(() => {
  if (props.id) {
    getDetails()
  }
  setData()
})
function setData() {
  let obj = {
    borrowDeptName: {
      label: '借用部门',
      value: 'borrowDeptName',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
    borrowUserName: {
      label: '借用人',
      value: 'borrowUserName',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
    preReturnTime: {
      label: '预计归还时间',
      value: 'preReturnTime',
      componentType: 'input',
      maxlength: 200,
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  console.log(
    proxy.$store.state.user.userInfo,
    'proxy.$store.state.user.userInfo'
  )
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function getCustomize() {
  let param = {
    tableKey:
      'assetBorrowRecordAddList-com.slip.spd.entity.vo.asset.useManage.AssetCanBorrowVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      if (props.orderId) {
        getMain()
      }
    }
  })
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function save(str = 'save') {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let api = props.id ? updateUseManagePage : addUseManagePage
      api(formInfo.value.data).then((res) => {
        if (res && res.success) {
          if (str === 'saveAndAdd') {
            proxy.$nextTick(() => {
              formInfo.value.ref.clearValidate()
            })
            emit('update:title', '新增设备启停')
          } else {
            //保存
            showDialog.value = false
            emit('returnModify')
          }
        }
      })
    }
  })
}
function getDetails() {
  getUseManageById(props.id).then((resp) => {
    if (resp && resp.success) {
      let data = resp.data
      formInfo.value.data = data
      formInfo.value.data.age = data.age == -2 ? '' : data.age
    }
  })
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  // flex: 1;
}
.flex-select :deep(.el-input--small .el-input__inner) {
  height: 28px !important;
}
:deep(.patrolPlan-checkbox) {
  padding: 0 5px 5px 5px;
  box-sizing: border-box;
  .el-checkbox-button__inner {
    width: 30px;
    height: 30px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-checkbox-button__inner) {
  border: 1px solid #dcdfe6 !important;
}
</style>
